import { message } from 'antd';
import { list, create, edit, dele, listSpecial } from '../services/classroom';
import tools from "../../../utils";

export default {
  namespace: 'classroom',

  state: {
    data: [],
    total: 0,
    success: true,
    treeData: [], // 开设专业数据
    mappingName: {}, // 根据专业id获取专业名称
  },

  effects: {
    *list({ payload }, { call, put }) {
      const response = yield call(list, payload);
      yield put({ type: 'callbackList', response });
    },
    *create({ payload }, { call, put }) {
      const response = yield call(create, payload);
      yield put({ type: 'callbackSave', response });
    },
    *edit({ payload }, { call, put }) {
      const response = yield call(edit, payload);
      yield put({ type: 'callbackSave', response });
    },
    *dele({ payload }, { call, put }) {
      const response = yield call(dele, payload);
      yield put({ type: 'callbackSave', response });
    },
    *listSpecial({ payload }, { call, put }) {
      const response = yield call(listSpecial, payload);
      yield put({ type: 'callbackListSpecial', response });
    },
  },

  reducers: {
    callbackList(st, { response }) {
      const state = st;
      if (response.success) {
        state.total = response.total;
        state.data = response.root
          .sort((a, b) => a.id - b.id)
          .sort((a, b) => a.specialId - b.specialId)
          .map(item => ({
            ...item,
            specialName: state.mappingName[item.specialId],
          }));
      }
      return { ...state };
    },
    callbackSave(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) message.success(response.msg);
      return { ...state };
    },
    callbackListSpecial(st, { response }) {
      const state = st;
      if (response.success) {
        const data = response.root;
        const treeData = [];

        for (let i = 0; i < data.length; i += 1) {
          const item = data[i];
          const { name, id, pid } = item;
          const isSpec = pid > 0; // 系部或专业: 0系部, >0专业
          treeData.push({
            id,
            pid,
            key: id,
            value: id,
            title: name,
            selectable: isSpec, // "专业"可供选择
          });
          if (isSpec) state.mappingName[id] = name;
        }

        state.treeData = tools.funcPidToChildren(treeData);
      }
      return { ...state };
    },
  },
};
